var localDB = require('nedb');

var app = require('electron').remote;
const appPath = app.app.getPath('appData') + '\\Requester';

var formatDoc = function (doc) {
    if ((typeof doc == 'object') && doc.constructor == Object) {
        var data = doc;
        data.id = doc._id;
        // data.createdAt = doc.createdAt.getTime();
        // data.updatedAt = doc.updatedAt.getTime();
        if (!data.hasOwnProperty('code')) {
            data.code = '';
        };
        if (!data.hasOwnProperty('formData')) {
            data.formData = '';
        };
        if (!data.hasOwnProperty('requestType')) {
            data.requestType = 'json';
        };

        delete data.createdAt;
        delete data.updatedAt;
        delete data.disable;
        delete data._id;
        return data;
    } else {
        return doc;
    };
};
// 格式化多行数据
var formatDocs = function (docs) {
    var _array = [];
    for (let i = 0; i < docs.length; i++) {
        const item = formatDoc(docs[i]);
        _array.push(item);
    };
    return _array;
};


var ContentData = function (options) {
    this.db = new localDB({
        filename: appPath + '/userDB/' + options.PorjectName + '_API' + '.db',
        autoload: true,
        timestampData: true,
    });
    this.openEvent = function () { };
    setTimeout(() => {
        this.openEvent();
    }, 10);
};

ContentData.prototype.onOpen = function (event) {
    this.openEvent = event;
};
ContentData.prototype.creat = function (data, cb) {
    this.db.insert({
        title: data.title,
        requestURL: data.requestURL,
        requestData: data.requestData,
        contentType: data.contentType, //{ type: String, enum: ['post', 'get', 'put', 'delete', 'folder'], required: true },
        header: data.header,
        contentIndex: data.contentIndex,
        parentId: data.parentId,
        description: data.description,
        disable: false,
        code: data.code,
        formData: data.formData,
        requestType: data.requestType,
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, formatDoc(doc));
        };
    });
};

ContentData.prototype.delete = function (id, cb) {
    this.db.findOne({ _id: id }, (error, doc) => {
        if (error) {
            cb(error, null);
        } else {
            this.db.update({ _id: id }, { $set: { disable: true } }, (error, _num) => {
                if (error) {
                    cb(false, doc);
                } else {
                    if (doc.contentType == 'folder') {
                        var parentId = doc.parentId;
                        this.db.update({ parentId: id }, { $set: { parentId: parentId } }, function (error, num) {
                            cb(false, num);
                        });
                    } else {
                        cb(false, _num);
                    };
                };
            });
        };
    });
};

ContentData.prototype.upData = function (id, data, cb) {
    this.db.update({ _id: id }, {
        $set: {
            title: data.title,
            requestURL: data.requestURL,
            requestData: data.requestData,
            header: data.header,
            contentType: data.contentType, //{ type: String, enum: ['post', 'get', 'put', 'delete', 'folder'], required: true },
            contentIndex: data.contentIndex,
            parentId: data.parentId,
            description: data.description,
            disable: false,
            code: data.code,
            formData: data.formData,
            requestType: data.requestType,
        }
    }, function (error, doc) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, doc);
        };
    });
};

ContentData.prototype.getAll = function (cb) {
    this.db.find({ $not: { disable: true } }, function (error, docs) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, formatDocs(docs));
        };
    });
};

ContentData.prototype.search = function (name, type, cb) {
    var query = {}
    if (type != 'ALL') {
        query.contentType = type;
    } else {
        query.$not = { contentType: 'folder' };
    };
    var re = null;
    if (name) {
        eval("re = /" + name.toString() + "/;");
    };
    if (re) {
        query.$or = [
            { requestURL: { $regex: re } },
            { title: { $regex: re } }
        ]
    };
    query.disable = false;
    if (name.toString().length > 30) {
        cb('too lang', null);
    } else {
        this.db.find(query, function (err, docs) {
            if (err) {
                cb(err.message, null);
            } else {
                cb(false, formatDocs(docs));
            };
        });
    };
};
ContentData.prototype.GetByArray = function (_array, cb) {
    this.db.find({
        disable: false,
        $not: { contentType: 'folder' },
        $where: function () {
            if ($.inArray(this._id, _array) >= 0) {
                return true;
            } else {
                return false;
            };
        }
    }, function (error, docs) {
        if (error) {
            cb(error, null);
        } else {
            cb(false, formatDocs(docs));
        };
    });
};



module.exports = function (options) {
    return new ContentData(options);
};